package com.xiongtian.stack;

/**
 * @author xiongtian
 * @version 1.0
 * @date 2021/3/18 16:13
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(10);
        for (int i = 0; i < 10; i++) {
            stack.push(i);
        }
        stack.show();

        stack.pop();
        stack.show();
    }
}

// 定义一个ArrayStack 表示栈
class ArrayStack {
    private int maxSize; // 栈大小
    private int[] stack; // 数组，数组 模拟栈，数据就放在该数组
    private int top = -1; //top表示栈顶，初始化为 -1

    // 构造器
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    // 栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    // 栈空
    public boolean isEmpty() {
        return top == -1;
    }

    // 入栈
    public void push(int val) {
        // 先判断栈时候满了
        if (isFull()) {
            System.out.println("栈满！");
            return;
        }
        top++;
        stack[top] = val;
    }

    public int pop() {
        // 先判断是否栈空
        if (isEmpty()) {
            System.out.println("栈空！");
            throw new RuntimeException("栈空!");
        }
        int result = stack[top];
        top--;
        System.out.println("出栈的元素为：" + result);
        return result;
    }

    // 显示栈的情况，【遍历栈】，遍历时，需要从栈顶开始显示数据
    public void show() {
        if (isEmpty()) {
            System.out.println("栈空，没有数据");
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d] = %d\n",i,stack[i] );
        }
    }
}